#include "Protocol.hpp"
#include "TcpSever.hpp"
#include "Calcute.hpp"
#include <unistd.h>
#include <memory>
using namespace network;
using namespace Protocal;

std::string HandlerRequest(std::string in,bool *err_code)
{
    Calcute g_calcute;
    std::string inbufferstream = in;
    std::unique_ptr<Factory> factory = std::make_unique<Factory>();
    auto req = factory->BuildRequest();
    // std::cout <<"in handler Request" <<std::endl;
    //      struct Request req;
    //  //    std::cout << sockp->GetSockfd() << std::endl;
    //      recv(sockp->GetSockfd(),&req,sizeof(req),0);
    //      req.debug();
    // 是否是一个完整的报文
    std::string total_resp;
    std::string message;
    while(Decode(inbufferstream, &message))
    {
        *err_code = true;
        return "";
     // 一定是完整报文，可以反序列化
    if (!req->deSerialize(message))
    {
        *err_code = false;
        return std::string();
    }
    // 业务处理
    auto resp = g_calcute.Cal(req);
    // 序列化
    std::string send_string;
    resp->Serialize(&send_string);
    // 构建响应及报文
    send_string = Encode(send_string);
    // 7.发送
    total_resp +=send_string;
    }
    return total_resp;
}

int main(int argc, char **argv)
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
    }

    uint16_t localport = std::stoi(argv[1]);
    std::unique_ptr<Tcpsever> svr(new Tcpsever(localport, HandlerRequest));
    svr->Loop();

    return 0;
}